package com.polaris.live.utils.route

import android.annotation.SuppressLint
import android.text.Spannable
import android.text.style.ClickableSpan
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.widget.TextView

/**
 * 点击事件
 *
 * @author Created by lucas on 2023/10/24 10:50
 * @since 1.0.0
 */
class ClickMovementMethod : OnTouchListener {

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouch(v: View, event: MotionEvent): Boolean {
        val widget = v as TextView
        // MovementMethod设为空，防止消费长按事件
        widget.movementMethod = null
        val text = widget.text
        val spannable = Spannable.Factory.getInstance().newSpannable(text)
        val action = event.action
        if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) {
            var x = event.x.toInt()
            var y = event.y.toInt()
            x -= widget.totalPaddingStart
            y -= widget.totalPaddingTop
            x += widget.scrollX
            y += widget.scrollY
            val layout = widget.layout
            val line = layout.getLineForVertical(y)
            val off = layout.getOffsetForHorizontal(line, x.toFloat())
            val link = spannable.getSpans(off, off, ClickableSpan::class.java)
            if (link.size != 0) {
                if (action == MotionEvent.ACTION_UP) {
                    link[0].onClick(widget)
                }
                return true
            }
        }
        return false
    }

    companion object {

        val instance: ClickMovementMethod by lazy { ClickMovementMethod() }

    }
}